//
//  DoctorReserveController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/26.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class DoctorReserveController: BaseViewController {
    
    private var viewModel: DoctorReserveViewModel? {
        didSet {
            tableView.reloadData()
        }
    }
    
    private var doctorType: DoctorType
    
    private var departmentId: String
    private var departmentName: String?
    private var code: String = ""
    private var isPrescription: String = ""
    private var diagType: Int
    
    /// 从眼科检查来
    private let fromMyopia: Bool
    private let recordId: String
    
    init(with doctorType: DoctorType = .all,
         departmentId: String = "",
         departmentName: String? = nil,
         recordId: String = "",
         fromMyopia: Bool = false) {
        self.doctorType = doctorType
        self.diagType = doctorType.rawValue
        self.departmentId = departmentId
        self.departmentName = departmentName
        
        self.recordId = recordId
        self.fromMyopia = fromMyopia
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupRefresh()
    }
    
    private var page = 1

    @IBOutlet private weak var topView: DoctorReserveTopView! {
        didSet {
            topView.delegate = self
            topView.configure(with: doctorType)
        }
    }
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(DoctorReserveCell.nibForCell(),
                               forCellReuseIdentifier: DoctorReserveCell.reuseIdentifier())
        }
    }
    
    private var alertView: DoctorReserveMenuView?
}

extension DoctorReserveController {
    private func setupUI() {
        let titleView = UINib.loadViewFrom(YSGSearchTitleView.self)
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
        navigationItem.titleView = titleView
        titleView.handlerClosure = { [weak self] _ in
            self?.presentSearchVc()
        }
        
        if departmentName != nil {
            topView.setTitle(departmentName, type: .department, isClicked: false)
        }
    }
    
    private func setupRefresh() {
        tableView.mj_header = refreshHeader(action: #selector(loadData))
        tableView.mj_header?.beginRefreshing()
        tableView.mj_footer = refreshFooter(action: #selector(loadMoreData))
    }
    
    private func endRefresh() {
        tableView.mj_header?.endRefreshing()
        tableView.mj_footer?.endRefreshing()
    }
    
    @objc private func loadData() {
        page = 1
        handleData(loadMore: false)
    }
    
    @objc private func loadMoreData() {
        page += 1
        handleData(loadMore: true)
    }
    
    private func handleData(loadMore: Bool) {
        DoctorReserveViewModel.getDoctorReserveList(type: doctorType == .advisory ? 0 : 1,
            departmentId: departmentId,
                                                    diagType: diagType,
                                                    current: page,
                                                    code: code,
                                                    isPrescription: isPrescription,
                                                    success: { models in
            self.endRefresh()
            if !loadMore {
                self.viewModel = DoctorReserveViewModel(models: models)
            } else {
                if models.count == 0 {
                    self.page -= 1
                } else {
                    self.viewModel?.loadMore(with: models)
                    self.tableView.reloadData()
                }
            }
        }) { errorMsg in
            self.endRefresh()
            if loadMore { self.page -= 1 }
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @objc private func presentSearchVc() {
        let resultVc = DoctorLIstResultViewController(doctorType: doctorType, recordId: recordId, fromMyopia: fromMyopia)
        navigationController?.pushViewController(resultVc, animated: true)
    }
}

extension DoctorReserveController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: DoctorReserveCell.reuseIdentifier(),
                                                 for: indexPath) as! DoctorReserveCell
        cell.delegate = self
        if let vm = viewModel?.viewModel(of: indexPath) {
            cell.configure(with: vm, type: doctorType)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let vm = viewModel?.viewModel(of: indexPath) else { return 0 }
        return vm.cellHeight(type: doctorType)
    }
}

extension DoctorReserveController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(of: indexPath) else { return }
        pushDoctorDetail(with: vm)
    }
    
    private func pushDoctorDetail(with vm: DoctorReserveRowViewModel) {
        switch doctorType {
        case .advisory:
            reserveAdvisory(vm, type: doctorType)
        default:
            let detailVc = DoctorDetailController(with: vm.doctorId)
            navigationController?.pushViewController(detailVc, animated: true)
        }
    }
}

extension DoctorReserveController: DoctorReserveTopViewDelegate {
    func didClickedDoctorReserveTopView(type: DoctorReserveTopViewType, dismiss: Bool) {
        if dismiss {
            alertView?.dismiss()
        } else {
            alertView = UINib.loadViewFrom(DoctorReserveMenuView.self)
            alertView?.frame = CGRect(x: 0, y: topView.bottom, width: screenW, height: screenH - topView.bottom)
            alertView?.show(in: view, type: type)
            alertView?.clickedClosure = { [weak self] (code, name) in
                guard let self = self else { return }
                switch type {
                case .department:
                    self.departmentId = code
                case .doctorType:
                    self.diagType = code.intValue
                case .office:
                    self.code = code
                case .prescription:
                    self.isPrescription = code
                }
                self.loadData()
                self.topView.setTitle(name, type: type)
            }
            
            alertView?.cancelClosure = { [weak self] in
                self?.topView.reset(type)
            }
        }
    }
}

extension DoctorReserveController: DoctorReserveCellDelegate {
    func doctorReserveCell(_ cell: DoctorReserveCell, willReserveCloud type: DoctorType) {
        guard let indexPath = tableView.indexPath(for: cell),
            let vm = viewModel?.viewModel(of: indexPath) else { return }
        reserveCloud(vm, type: type)
    }
    
    func doctorReserveCell(_ cell: DoctorReserveCell, willReserveAdvisory type: DoctorType) {
        guard let indexPath = tableView.indexPath(for: cell),
            let vm = viewModel?.viewModel(of: indexPath) else { return }
        reserveAdvisory(vm, type: type)
    }
}

// MARK: - Helpers
extension DoctorReserveController {
    private func reserveAdvisory(_ vm: DoctorReserveRowViewModel, type: DoctorType) {
        
        let model = DoctorDetail(id: vm.doctorId,
                                 deptId: vm.departmentId,
                                 docName: vm.doctorName,
                                 deptName: vm.department,
                                 hospitalName: vm.hospitalName,
                                 jobTitleName: vm.office,
                                 docGoodAtNames: vm.specialty,
                                 thumbnailUrl: vm.thumbnailUrl,
                                 score: vm.score.floatValue,
                                 fee: vm.fee,
                                 diagType: type.rawValue)
        let doctorDetail = DoctorDetailViewModel(model: model,
                                                 selectType: .advisory)
//        let newAdvisoryVc = NewAdvisoryController(with: doctorDetail, recordId: recordId, fromMyopia: fromMyopia)
//        navigationController?.pushViewController(newAdvisoryVc, animated: true)
        
        
        let adMedicalRecordsVC = AdMedicalRecordsController()
        adMedicalRecordsVC.doctorVm = doctorDetail
        adMedicalRecordsVC.recordId = recordId
        adMedicalRecordsVC.fromMyopia = fromMyopia
        navigationController?.pushViewController(adMedicalRecordsVC, animated: true)
    }
    
    private func reserveCloud(_ vm: DoctorReserveRowViewModel, type: DoctorType) {
        let model = DoctorDetail(id: vm.doctorId,
                                 deptId: vm.departmentId,
                                 docName: vm.doctorName,
                                 deptName: vm.department,
                                 hospitalName: vm.hospitalName,
                                 jobTitleName: vm.office,
                                 docGoodAtNames: vm.specialty,
                                 thumbnailUrl: vm.thumbnailUrl,
                                 score: vm.score.floatValue,
                                 fee: vm.fee,
                                 diagType: type.rawValue)
        let doctorDetail = DoctorDetailViewModel(model: model,
                                                 selectType: .cloud)
        let newCloudVc = NewCloudReserveController(with: doctorDetail)
        navigationController?.pushViewController(newCloudVc, animated: true)
    }
}

